/*实现栈*/


///栈中元素节点
struct Node{
    value: String,
    next: Option<Box<Node>>,//下一个节点
}

impl Node {
    fn new(value: String) -> Node {
        Node {
            value,
            next: None
        }
    }
}

///栈
struct Stack{
    size: u32, //大小
    top: Option<Box<Node>>
}
///方法
impl Stack {
    ///创建栈
    fn new() -> Stack {
        Stack {
            size: 0,
            top: None
        }
    }
    ///压栈
    fn push(&mut self, value: String) {
        let mut node = Node::new(value);
        //take方法可以从Option中取出值，为原来的Option变量留下None值，但原来的变量还有效（但实际上没什么用处了，因为只剩下None了）。take方法的原始值或者引用必须为mut类型
        let next = self.top.take();
        node.next = next;
        self.top = Some(Box::new(node));
        self.size += 1;
    }
    ///弹栈
    fn pop(&mut self) -> Option<String> {
        let top = self.top.take();
        match top {
            Some(mut x) => {
                self.top = x.next.take();
                self.size -= 1;
                Some(x.value)
            },
            None =>None,
        }
    }
}

pub fn stack_demo(){
    let mut stack = Stack::new();
    stack.push(String::from("hello"));
    stack.push(String::from("world"));
    println!("{}", stack.size);

    let top = stack.pop();
    match top {
        Some(s) => println!("{}", s),
        None => {}
    }
    println!("{}", stack.size);
}